<template>
   <div class="main">
      <div class="search">
         <label>商品搜索：</label>
         <el-input v-model="it.name" style="width: 240px" placeholder="请输入商品名称 " clearable>
         </el-input>
         <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
         <el-button class="button" :icon="Plus" @click="add">添加</el-button>
         <el-button class="button" :icon="Delete" @click="deleteRows">批量删除</el-button>
      </div>
      <div class="data">
         <div class="gird">
            <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
               :cell-style="{ textAlign: 'center' }" ref="tableRef">
               <el-table-column type="selection" width="55" />
               <el-table-column prop="id" label="编号" width="60" />
               <el-table-column prop="image" label="商品主图" width="180" align="center">
                  <template #default="scope">
                     <div class="row-image" :style="'background-image:url(' + scope.row.pic + ')'"></div>
                  </template>
               </el-table-column>
               <el-table-column prop="name" label="商品名称" width="120" />
               <el-table-column prop="brand.name" label="品牌" width="80">
                  <template #default="scope">
                     {{ scope.row.brand?.name || '' }}
                  </template>
               </el-table-column>
               <el-table-column prop="category.name" label="类别名称" width="120">
                  <template #default="scope">
                     {{ scope.row.category?.name || '' }}
                  </template>
               </el-table-column>
               <el-table-column label="价格" width="120">
                  <template #default="scope">
                     {{ (scope.row.price || 0).toFixed(2) }}
                  </template>
               </el-table-column>

               <el-table-column label="售卖价格" width="120">
                  <template #default="scope">
                     {{ (scope.row.sellPrice || 0).toFixed(2) }}
                  </template>
               </el-table-column>
               <el-table-column prop="publishStatus" label="是否下架" width="100">
                  <template #default="scope">
                     <el-switch v-model="scope.row.publishStatus" @change="updatePublish(scope.row)" />
                  </template>
               </el-table-column>
               <el-table-column prop="newStatus" label="是否为热门" width="100">
                  <template #default="scope">
                     <el-switch v-model="scope.row.newStatus" @change="updateNew(scope.row)" />
                  </template>
               </el-table-column>
               <el-table-column prop="qty" label="库存数量" width="120" />
               <el-table-column prop="sold" label="销量" width="120" />
               <el-table-column fixed="right" label="操作" min-width="200">
                  <template #default="scope">
                     <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">删除
                     </el-button>
                     <el-button type="primary" :icon="Edit" @click="editRow(scope.row)" size="small">编辑</el-button>
                  </template>
               </el-table-column>
            </el-table>
         </div>
         <!-- 分页 -->
         <div class="pagination" style="margin-top: 10px;">
            <el-pagination v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize"
               :page-sizes="[5, 10, 15, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pi.total"
               background @current-change="handleCurrentChange" @size-change="handleSizeChange" />
         </div>
      </div>
      <el-dialog v-model="show" :title="title" width="800" draggable :close-on-click-modal="false">
         <!-- 新增操作的表单 -->
         <el-form :model="itm" ref="sfRef">
            <el-row>
               <el-col :span="12" label-width="100px">
                  <el-form-item label="商品名称:" label-width="100px" prop="name">
                     <el-input placeholder="请输入商品名称" v-model="itm.name" />
                  </el-form-item>
                  <el-form-item label="商品品牌:" label-width="100px" prop="brandId">
                     <el-select placeholder="请选择商品品牌" v-model="itm.brandId" clearable>
                        <el-option 
                           v-for="item in brands" 
                           :key="item.id" 
                           :label="item.name || item.label || ''" 
                           :value="item.id || item.value || ''" />
                     </el-select>
                  </el-form-item>
                  <el-form-item label="售卖价格:" label-width="100px" prop="sellPrice">
                     <el-input placeholder="请输入售卖价格" v-model="itm.sellPrice" />
                  </el-form-item>
                  <el-form-item label="库存数量:" label-width="100px" prop="number">
                     <el-input placeholder="请输入库存数量" v-model="itm.number" />
                  </el-form-item>
                  <el-form-item label="商品价格:" label-width="100px" prop="price">
                     <el-input placeholder="请输入商品价格" v-model="itm.price" />
                  </el-form-item>
                  <el-form-item label="是否下架:" label-width="100px" prop="publishStatus">
                     <el-switch v-model="itm.publishStatus" />
                  </el-form-item>
                  <el-form-item label="是否热门:" label-width="100px" prop="newStatus">
                     <el-switch v-model="itm.newStatus" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="商品主图片:" label-width="100" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :auto-upload="true"
                        :show-file-list="false"
                        action="/api/shop-upload-api/upload"
                        name="file"
                        :on-success="uploadSuccess"
                        :before-upload="beforeUpload"
                    >
                      <img v-if="itm.pic" :src="itm.pic" class="logo-circle-preview" />
                      <div v-else class="upload-placeholder">
                        <el-icon class="logo-uploader-icon"><Plus /></el-icon>
                        <div class="upload-text">上传图片</div>
                      </div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="商品类别" prop="categoryId">
                     <el-cascader 
                        placeholder="请选择商品类别" 
                        v-model="itm.categoryId" 
                        :options="camTreeData"
                        :props="{ emitPath: false, value: 'id', label: 'name' }"
                        :render-after-expand="false" 
                        clearable
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="商品描述:" label-width="100px" prop="name">
                     <el-input placeholder="请输入商品描述" v-model="itm.description" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="商品销量:" label-width="100px" prop="name">
                     <el-input placeholder="请输入商品销量" v-model="itm.sold" />
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="show = false">取消</el-button>
               <el-button type="primary" @click="submitForm">确认</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>
<script setup>
import { ref, onMounted, toRaw, nextTick } from 'vue'
import { findAll, updatePublicStatus, updateNewStatus, updateRecommandStatus, deleteById, deleteAll, save, update as updateItem } from '@/api/ItemApi'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { findTree as findAllItemCategory } from '@/api/ItemCategoryApi';
import { findAll as findAllBrand } from '@/api/BrandApi';
import { ca } from 'element-plus/es/locales.mjs';
onMounted(() => {
   search();
})
const brands = ref([]);
findAllB();
async function findAllB() {
   try {
      let resp = await findAllBrand();
      console.log("Brand API Response:", resp);
      // 检查响应数据结构并正确设置brands.value
      if (resp && resp.records && Array.isArray(resp.records)) {
         brands.value = resp.records;
      } else if (resp && resp.brands && Array.isArray(resp.brands)) {
         brands.value = resp.brands;
      } else if (resp && Array.isArray(resp)) {
         brands.value = resp;
      } else {
         brands.value = [];
      }
      console.log("Processed brands:", brands.value);
   } catch (error) {
      console.error("获取品牌数据失败:", error);
      brands.value = [];
   }
}
const tableData = ref();
const it = ref({
   name: "",
});
//分页信息
const pi = ref({
   pageNo: 1,
   pageSize: 5,
   total: 0,
});

async function search() {
   let params = it.value;
   let resp = await findAll(pi.value.pageNo, pi.value.pageSize, params);
   console.log(resp);
   tableData.value = resp.records;
   
   // 确保pi对象正确更新
   if (resp) {
      pi.value.pageNo = resp.current || 1;
      pi.value.pageSize = resp.size || 5;
      pi.value.total = resp.total || 0;
   }
   
   // 转换状态字段 0/1 为 false/true，确保与表格显示一致
   if (tableData.value) {
      tableData.value = tableData.value.map(item => ({
         ...item,
         publishStatus: item.publishStatus === 1,
         newStatus: item.newStatus === 1,
         recommandStatus: item.recommandStatus === 1
      }));
   }
}

//分页查询
function handleCurrentChange(val) {
   pi.value.pageNo = val;
   search();
}

function handleSizeChange(val) {
   pi.value.pageSize = val;
   pi.value.pageNo = 1; // 重置到第一页
   search();
}
const uploadSuccess = (result) => {
  itm.value.pic = result.data;
  // console.log(result.data);
}
async function updatePublish(row) {
   //  console.log(row.publishStatus);
   if (row.publishStatus === false) {
      let resp = await updatePublicStatus(row.id, 0);
      if (resp.code == 200) {
         ElMessage({
            message: "商品下架",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
   else {
      let resp = await updatePublicStatus(row.id, 1);
      if (resp.code == 200) {
         ElMessage({
            message: "商品上架",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
}
async function updateNew(row) {
   if (row.newStatus == false) {
      let resp = await updateNewStatus(row.id, 0);
      if (resp.code === 200) {
         ElMessage({
            message: "取消热门",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
   else {
      let resp = await updateNewStatus(row.id, 1);
      if (resp.code === 200) {
         ElMessage({
            message: "设为热门",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
}
async function updateRecommand(row) {
   if (row.recommandStatus === false) {
      let resp = await updateRecommandStatus(row.id, 0);
      if (resp.code === 200) {
         ElMessage({
            message: "不推荐",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
   else {
      let resp = await updateRecommandStatus(row.id, 1);
      if (resp.code === 200) {
         ElMessage({
            message: "设为推荐商品",
            type: "success",
         });
      }
      else {
         ElMessage({
            message: resp.msg,
            type: "error",
         });
      }
   }
}
function deleteRow(row) {
   let id = row.id;
   // console.log(id);
   deleteItem(id);
}
async function deleteItem(id) {
   ElMessageBox.confirm("是否确认删除所选行?", "警告！", {
      type: "warning",
   })
      .then(async () => {
         let resp = await deleteById(id);
         if (resp.code == 200) {
            ElMessage({
               message: "删除成功",
               type: "success",
            });
            search();
         } else {
            ElMessage({
               message: resp.msg || "删除失败",
               type: "error",
            });
         }
      })
      .catch(() => { });
}
// 上传前检查
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
//点击行数后单选框被勾选
let tableRef;
//批量删除
function deleteRows() {
   try {
      let rows = tableRef.getSelectionRows();
      console.log("选中的行:", rows);
      
      if (!rows || rows.length === 0) {
         ElMessage({
            message: "请至少选择一行进行删除",
            type: "warning",
         });
         return;
      }
      
      let ids = [];
      for (let row of rows) {
         if (row && row.id) {
            ids.push(toRaw(row).id);
         }
      }
      
      if (ids.length === 0) {
         ElMessage({
            message: "未能获取选中行的有效ID",
            type: "warning",
         });
         return;
      }
      
      console.log("准备删除的ID列表:", ids);
      deleteAllRows(ids);
   } catch (error) {
      console.error("获取选中行时发生错误:", error);
      ElMessage({
         message: "操作失败，请稍后重试",
         type: "error",
      });
   }
}
async function deleteAllRows(ids) {
   if (!ids || ids.length == 0) {
      ElMessage({
         message: "请选择想要删除的行",
         type: "warning",
      });
      return;
   }
   
   ElMessageBox.confirm(`是否确认删除所选的${ids.length}行数据?`, "删除确认", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消"
   })
      .then(async () => {
         try {
            //向后台发送ajax请求
            let resp = await deleteAll(ids);
            if (resp.code == 200) {
               ElMessage({
                  message: resp.msg || `成功删除${ids.length}条数据`,
                  type: "success",
               });
               search();
            } else {
               ElMessage({
                  message: resp.msg || "删除失败",
                  type: "error",
               });
            }
         } catch (error) {
            console.error("删除过程中发生错误:", error);
            ElMessage({
               message: "删除请求失败，请稍后重试",
               type: "error",
            });
         }
      })
      .catch(() => {
         ElMessage({
            message: "已取消删除操作",
            type: "info",
         });
      });
}
const camTreeData = ref([]);
const show = ref(false);
const title = ref("新增商品");
const itm = ref({
   name: "",
   price: "",
   sellPrice: "",
   number: "",
   brandId: "",
   categoryId: [],
   pic: "",
   description: "",
   sold: "",
   publishStatus: false,
   newStatus: false
});
async function findAllCategory() {
   try {
      let resp1 = await findAllItemCategory();
      console.log("Category API Response:", resp1);
      let tree = [];
      if (resp1 && resp1.children) {
         tree = resp1.children;
      } else if (resp1 && Array.isArray(resp1)) {
         tree = resp1;
      }
      buildTree(tree);
      camTreeData.value = tree;
      console.log("Processed category tree:", camTreeData.value);
   } catch (error) {
      console.error("获取商品类别数据失败:", error);
      camTreeData.value = [];
   }
}
async function add() {
   show.value = true;
   title.value = "新增商品";
   // 确保所有字段都被正确重置
   itm.value = {
      name: "",
      price: "",
      sellPrice: "",
      number: "",
      brandId: "",
      categoryId: [],
      pic: "",  // 确保图片字段被清空
      description: "",
      sold: "",
      publishStatus: false,
      newStatus: false
   }
   
   // 确保数据加载完成
   await Promise.all([
      findAllB(),
      findAllCategory()
   ]);
}
function buildTree(noArray) {
   if (!Array.isArray(noArray)) return;
   
   for (let node of noArray) {
      if (!node) continue;
      
      // 确保每个节点都有name和id属性
      node.label = node.name || '';
      node.value = node.id || '';
      
      // 确保子节点也正确处理
      if (Array.isArray(node.children) && node.children.length > 0) {
         buildTree(node.children);
      }
   }
}
function submitForm() {
   let idm = toRaw(itm.value);
   
   // 处理商品类别ID
   // 由于使用了 emitPath: false，categoryId 直接是选中的值而不是数组
   if (idm.categoryId === null || idm.categoryId === undefined || idm.categoryId === '') {
      idm.categoryId = null;
   }
   // 如果仍然接收到数组（可能由于某些配置问题），则取最后一个元素
   else if (Array.isArray(idm.categoryId) && idm.categoryId.length > 0) {
      idm.categoryId = idm.categoryId[idm.categoryId.length - 1];
   }
   // 否则保持原值不变
   
   // console.log(idm);
   
   // 将开关字段转换为后端需要的值（1或0）
   idm.publishStatus = idm.publishStatus ? 1 : 0;
   idm.newStatus = idm.newStatus ? 1 : 0;
   
   if (idm.id) {
      update(idm);
   } else {
      addItem(idm);
   }
}
async function addItem(idm) {
   console.log("准备提交的商品数据:", idm);
   let resp = await save(idm);
   console.log("后端返回结果:", resp);
   if (resp.code == 200) {
      ElMessage({
         message: "添加成功",
         type: "success",
      });
      search();
      show.value = false;
   } else {
      ElMessage({
         message: resp.msg || "添加失败",
         type: "error",
      });
   }
}
function editRow(row) {
   findAllCategory();
   row = Object.assign({}, row);
   console.log(row);
   show.value = true;
   title.value = "修改商品";
   
   // 将数字状态转换为布尔值用于开关组件
   row.publishStatus = row.publishStatus === 1;
   row.newStatus = row.newStatus === 1;
   row.recommandStatus = row.recommandStatus === 1;
   
   nextTick(() => {
      itm.value = row;
   });
}
async function update(idm) {
   let resp = await updateItem(idm);
   if (resp.code == 200) {
      ElMessage({
         message: "修改成功",
         type: 'success',
      });
      search();
      show.value = false;
   } else {
      ElMessage({
         message: resp.msg || "修改失败",
         type: 'error',
      });
   }
}

//头像上传成功时的回调函数
function imageSuccess(resp, file) {

   if (resp.success) {
      itm.value.image = resp.url;
      console.log(resp);
   }
}
</script>
<style scoped>
.main {
   padding: 0 20px;
   position: relative;
   /* 确保 main 元素对话框的绝对定位 */
}

.data>.pagination {
   margin-top: 10px;
   float: right;
}

.data {
   margin-top: 20px;
}

.search {
   margin-top: 10px;
   margin-bottom: 10px;
   padding: 20px;
   border: 1px solid #ebeef5;
}

.search>.button {
   float: right;
}

.el-table td.is-center,
.el-table th.is-center {
   text-align: center;
}

/* 需要时加入的对话框动画样式 */

.dialog-enter,
.dialog-leave-to

/* .dialog-leave-active in <2.1.8 */
   {
   opacity: 0;
}

.image {
   width: 180px;
   height: 180px;
   border: 1px solid #ccc;
}

.image .icon {
   width: 180px;
   height: 180px;
}

.image .preview {
   width: 180px;
   height: 180px;
   background-position: center center;
   background-repeat: no-repeat;
   background-size: contain;
}

.row-image {
   height: 80px;
   background-position: center center;
   background-repeat: no-repeat;
   background-size: contain;

}

.logo-circle-preview {
   width: 120px;
   height: 120px;
   border-radius: 50%;
   object-fit: cover;
   z-index: 1;
   position: relative;
}
</style>